package com.zb.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zb.entity.Sms;
import com.zb.exception.SMSException;
import com.zb.yaml.SmsSecret;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author WEN
 * @Date 2023/7/10 0010
 **/
@Log4j2
public class SmsSendUtil {
    /**
     * 发送短信验证码
     * @param phone 接收者手机号
     * @param code 验证码
     * @return
     */
    public static void sendVerifiCode(String phone, String code) throws SMSException {
        sendSms(Sms.verifCode(phone, code));
    }
    /**
     * 发送短信核销码
     * @param phone 接收者手机号
     * @param code 验证码
     * @return
     */
    public static void sendWriteOffCode(String phone, String code) throws SMSException {
        sendSms(Sms.writeOffCode(phone, code));
    }



    public static void sendSms(Sms sms) throws SMSException {
        IAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile(sms.getRegionId(), SmsSecret.accessKeyId(), SmsSecret.secret()));
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(SmsSecret.domain());
        request.setVersion(SmsSecret.version());
        request.setAction(SmsSecret.action());
        request.putQueryParameter("AccessKeyId", SmsSecret.accessKeyId());
        request.putQueryParameter("PhoneNumbers", sms.getPhoneNumbers());
        request.putQueryParameter("SignName", sms.getSignName());
        request.putQueryParameter("TemplateCode", sms.getTemplateCode());
        request.putQueryParameter("TemplateParam", sms.getTemplateParam());
        if (StringUtils.isNotBlank(sms.getSmsUpExtendCode())) {
            request.putQueryParameter("SmsUpExtendCode", sms.getSmsUpExtendCode());
        }
        if (StringUtils.isNotBlank(sms.getOutId())) {
            request.putQueryParameter("OutId", sms.getOutId());
        }

        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            throw new SMSException("短信发送失败：" + e);
        }
        JSONObject resObj = JSON.parseObject(response.getData(), JSONObject.class);
        log.info("短信发送结果：{}", resObj);
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.equals("OK", resObj.getString("Code"))) {
            return;
        }
        SmsStatusCodeUtil.smsStatusCode(resObj);
    }
}
